package zezutom.joker.service;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.transaction.annotation.Transactional;
import zezutom.joker.model.Joker;
import zezutom.joker.model.BadJokeException;
import zezutom.joker.model.Joke;
import zezutom.joker.model.JokeSeverity;
import zezutom.joker.model.Popularity;
import zezutom.joker.model.RepeatedJokeException;

/**
 *
 * @author tomasz
 */
public class FunnyServiceImpl implements FunnyService {

    @PersistenceContext(name="persistenceUnit")
    private EntityManager entityManager;
    
    @Transactional(rollbackFor={BadJokeException.class, RepeatedJokeException.class})
    @Override
    public Collection<Joke> saySomethingFunny(Long id) throws BadJokeException, RepeatedJokeException {
        Joker joker = loadClown(id);
        
        List<Joke> toldJokes = new ArrayList<Joke>();
       
        // promote the Joker now: very unwise, see exceptions below
        joker.setPopularity(Popularity.FAMOUS);
        
        if (joker.getId() == null) {
            entityManager.persist(joker);
        } else {
            entityManager.merge(joker);
        }        
        
        for (Joke joke : joker.getJokes()) {
            if (JokeSeverity.DEADLY.equals(joke.getSeverity())) {
                throw new BadJokeException();
            }
            
            if (toldJokes.contains(joke)) {
                throw new RepeatedJokeException();
            }
            toldJokes.add(joke);
        }
               
        return toldJokes;
    }

    @Override
    public Collection<Joker> loadCircus() {
        return entityManager.createQuery("select j from Joker j").getResultList();
    }

    @Override
    public Joker loadClown(Long id) {
        return entityManager.find(Joker.class, id);
    }    
}
